var menuLength=getLength("config_page_size");
// jQuery Datatable 对象
var searchTable;
var searchOrgTable;
// 组织及角色信息
var checkAccount = false;
var orgTree;
// 后面构建btn 代码
var btnModel = '    \
	{{#each func}}\
    <button type="button" class="{{this.type}} btn-sm" onclick="{{this.fn}}">{{this.name}}</button>\
    {{/each}}';
var template = Handlebars.compile(btnModel);
(function($) {
    $.fn.bootstrapValidator.validators.loginNameCheck = {
        html5Attributes: {
            message: 'message',
            field: 'field'
        },
        validate: function(validator, $field, options) {
            return true;
        }
    };
}(window.jQuery));
//输入校验条件
var validator = {
	message : '请核对此字段的输入',
	feedbackIcons : {
		valid : 'glyphicon glyphicon-ok',
		invalid : 'glyphicon glyphicon-remove',
		validating : 'glyphicon glyphicon-refresh'
	},
	submitHandler: function(validator, form, submitButton) {
		var id=submitButton.attr("id");
		if(id=="saveBtn"){
		  saveSysStaff();
		}
		if(id=="updateBtn"){
			  updateSysStaff();
		}
	  },
	fields : {
		loginName: {
			validators : {
				notEmpty : { message : '请输入账号' },
				stringLength: { min: 0, max: 20, message: '请输入不超过20个字符' },
				regexp: { regexp: /^[a-zA-Z0-9_\-\.]+$/, message: '用户名由数字字母-_和.组成'},
				loginNameCheck:{message:'账号已经被占用'}
			}
		},
		passwd : {
			validators : {
				notEmpty : { message : '请输入密码' },
				stringLength: { min: 3, max: 20, message: '请输入3~20个字符' }
			}
		},
		staffName : {
			validators : {
				notEmpty : { message : '请输入人员姓名' },
				stringLength: { min: 0, max: 15, message: '请输入不超过15个字' }
			}
		},
		orgName : {
			validators : {
				notEmpty : { message : '请选择所属组织' }
			}
		},
		empCode : {
			validators : {
				regexp : {
					regexp : /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/,
					message : '请输入15或18位身份证号'
				}
			}
		},
		email : {
			validators : {
				emailAddress : { message : '请检查Email拼写' },
				stringLength: { min: 0, max: 50, message: '请输入不超过50个字符' }
			}
		},
		postcode : {
			validators : {
				regexp : { regexp : /^[0-9]+$/, message : '请检查邮政编码' },
				stringLength: { min: 0, max: 6, message: '请输入不超过6位数字' }
			}
		},
		mailAddr : {
			validators : {
				stringLength: { min: 0, max: 20, message: '请输入不超过20个字符' }
			}
		},
		phone: {
			validators : {
				regexp : {
					regexp : /(^(\d{3,4}-)?\d{7,8})$|(1[3|5|7|8]{1}[0-9]{9})/,
					message : '请检查电话是否正确'
				}
			}
		},
		mobilPhone: {
			validators : {
				notEmpty : { message : '请输入手机号' },
				stringLength: { min: 11, max: 11, message: '请输入11位手机号码' },
                regexp: { regexp: /^1[3|5|7|8]{1}[0-9]{9}$/, message: '请输入正确的手机号码' }
			}
		},
		staffSort: {
			validators : {
				stringLength: {min: 0, max: 8, message: '请输入不超过8位数字' },
				regexp: { regexp: /^[0-9]+$/, message: '排序只能输入数字'}
			}
		}
	}
};
//数据表格的配置（甲方表格）
var tableOption ={
	"ordering": false,// 排序
	"serverSide": true,// 开启服务器模式
    scrollX:true,
    fixedColumns:{
        leftColumns: 2
    },
   lengthMenu: [
         menuLength,
         menuLength  // [10,25], [10,25]
    ],
	ajax: {
        "type": "POST",
        "url":'searchMap4Page.action',//请求路径
        "contentType": 'application/x-www-form-urlencoded; charset=UTF-8',
        "dataType":'json',
        "data":function(d){// 查询参数
        	d.staffName = $('#searchStaffName').val();
        	d.loginName = $('#searchLoginName').val();
        	d.orgId = $('#searchOrgId').val();
        	d.attrc = $('#searchStaffOrgStatus').val();
        	d.staffKind = 1;
        	return d;
        }
	},            
	columns: [// 对应列
	    {"data": null,"title":"操作",className:"text-center",render: function (a, b, c, d) {
        	var btnArray = new Array();
    		if(hadPermission.update){
    			btnArray.push({"name": "修改", "fn": "showEditPage(\'" + c.staffId + "\')", "type": "user-button"});
    		}
    		if(hadPermission.update && varStaffKind==='1' ){
    			btnArray.push({"name":"角色管理","fn":"addRoleX('"+c.staffOrgId+"','"+c.staffName+"','"+c.orgName+"')","type":"user-button"});
    		}
    		if(hadPermission.update){
    			btnArray.push({"name":"岗位管理","fn":"orgManage('"+c.staffId+"','"+c.staffName+"','"+c.orgName+"')","type":"user-button"});
    		}
    		if(hadPermission.update){
    			btnArray.push({"name":"密码重置","fn":"resetPasswd('"+c.staffId + "\',\'" + c.staffName + "\')","type":"user-button"});
    		}
    		if(hadPermission.del && varStaffKind==='1'){
    			//btnArray.push({"name": "删除", "fn": "del(\'" + c.staffId + "\',\'" + c.staffName + "\')", "type": "user-button user-btn-n"});
    			if(c.staffOrgStatus=='1'){
    				btnArray.push({"name": "禁用", "fn": "changeStaffOrgStatus(\'"+c.staffOrgId+"\',\'"+c.staffName+"\',\'"+c.orgName+"\',\'0\')", "type": "user-button user-btn-n"});
    			}else{
    				btnArray.push({"name": "启用", "fn": "changeStaffOrgStatus(\'"+c.staffOrgId+"\',\'"+c.staffName+"\',\'"+c.orgName+"\',\'1\')", "type": "user-button"});
	    		}
    		}
    		context = {
    				func:btnArray
    		}
    		var html = template(context);
    		return html;
    	}},
        {"data": "staffName","title":"人员姓名",className: "text-center",render:function(a,b,c,d){
        	return "<a href=\"javascript:doDetail('"+c.staffId+"')\">"+a+"</a>";
        }},
        {"data": "loginName","title":"账号",width:"120",className: "text-center"},
        {"data": "orgName","title":"岗位",className: "text-center"},
        {"data": "sex","title":"性别",className: "text-center",render: function (a, b, c, d) {
            return c.sex=='M'?'男':'女';
        }},
        {"data": "phone","title":"电话号码",width:"120",className: "text-center"},
        {"data": "email","title":"邮箱账号",width:"180",className: "text-center"},
        {"data": "mobilPhone","title":"手机号码",width:"120",className: "text-center"},
        {"data": "staffOrgStatus","title":"岗位状态",className: "text-center",render: function (a, b, c, d){
			if('1' == a)return '有效';else return '无效';
		}},
	    {"data": "staffOrgId","title":"id","visible": false }
    ],
    "columnDefs": [
		{// 所有列默认值
			"targets": "_all",
			"defaultContent": '',
			render: $.fn.dataTable.render.ellipsis(22, true)
		}],
		 "dom": 'rt<"pull-left mt5"l><"pull-left mt5"i><"pull-right mt5"p><"clear">' //生成样式
};

// 初始化页面
function initFrame(){
	checkAccount = false;
	$('#saveBtn').hide();
	$('#updateBtn').hide();
	$("#orgContainer").hide();
	$('#sysStaffObjectForm input').val('');
	if($("#partner").hasClass("active")){//如果当前是乙方标签页激活中
		searchTableForPartner.ajax.reload();
		return;
	}
	searchTable.ajax.reload();
	$('#sysStaffObjectForm').bootstrapValidator('resetForm',true);
}

// 展示查询页面
function staffSearch(){
	$('#statusStaffObjdiv').hide();
	$('#staffContainer').hide();
	$('#myTabContent').show();
	$('#faDIV').hide();
	initFrame();
}

// 查询
function search4Page(){
	var staffKind = $("#currentStaffKind").val();
	if(1 == staffKind){//如果是1，刷新方列表
		$("#searchTable").DataTable().draw(false);
		return;
	}else if(2 == staffKind){
		$("#searchTable").DataTable().draw(false);
		
	}
}

// 展示添加页面
function showAddPage(){
	var staffKind = $("currentStaffKind").val();
	$("#orgOperation").hide();
	$('#saveBtn').show();
	$('#updateBtn').hide();
	validator.fields.passwd.validators = {
			notEmpty : { message : '请输入密码' },
			stringLength: { min: 3, max: 20, message: '请输入3~20个字符' }
	};
	if(null == $('#sysStaffObjectForm').data('bootstrapValidator')) {
		$('#sysStaffObjectForm').bootstrapValidator(validator);
	}
	$('#sysStaffObjectForm input').val('');
	$('#sysStaffObjectForm').bootstrapValidator('resetForm',true);
	$('#orgName').attr("onclick","selectTree('yourOrgFun');");
	$(".staffList").hide();
	$(".staffUpdate").show();
	$("#staffKindStaffObj").val(staffKind);
	$("#disId").val(disId);
}

//设置树参数
var settingTree = {
		data: {
			key:{
              name:"name"
          },
			simpleData: {
				enable: true,
				idKey:"id", 
	            pIdKey:"pId"
			}
		},
		callback: {
			beforeClick: function(treeId, treeNode) {}
		},
		async:{
			enable: true,
			url:"../sysOrgController/loadOrgTreeData",
			autoParam:["id=pid"]
		}
	};
//展示添加表单组织树
function selectTree(yourOrgFunForAdd){
	var staffKind = $("#staffKindStaffObj").val();
	var disId = $("#disId").val();
	if(staffKind == 1){
		showTree($("#orgName"),$("#faDIV"));
	}else {
		showOrgTreeForPartnerForAdd(disId,'yourOrgFunForAdd');
	}
	
}
//展示甲方查询条件组织树
function showOrgTreeForHome(){
	showTree($("#searchOrgName"),$("#searchHomeOrgDIV"));
}


function yourOrgFun(orgId, orgName, orgCode) {
	  //alert("orgId=" + orgId + ",orgName=" + orgName + ",orgCode=" + orgCode);
	  $("#searchPartnerOrgName").val(orgName);
	  $("#searchPartnerOrgId").val(orgId);
	  $('#NoPermissionModal').modal("hide");
	}
function yourOrgFunForAdd(orgId, orgName, orgCode){
	  $("#orgName").val(orgName);
	  $("#orgId").val(orgId);
	  if($('#sysStaffObjectForm').data('bootstrapValidator')){
			$('#sysStaffObjectForm').data('bootstrapValidator').updateStatus('orgName', 'NOT_VALIDATED', null).validateField('orgName');
	  }
	  $('#NoPermissionModal').modal("hide");
}

//展示乙方查询条件组织树
function showOrgTreeForPartner(disId,yourOrgFun){
//	showTree($("#searchPartnerOrgName"),$("#searchPartnerOrgDIV"));
	var frameSrc =prc+"/sysOrgController/toPartnerOrgList"+"?disId="+disId+"&yourFun="+yourOrgFun; 
  $("#NoPermissioniframe").attr("src", frameSrc);  
  $('#NoPermissionModal').modal({ show: true, backdrop: 'static' });
}
function showOrgTreeForPartnerForAdd(disId,yourOrgFunForAdd){
	var frameSrc =prc+"/sysOrgController/toPartnerOrgList"+"?disId="+disId+"&yourFun="+yourOrgFunForAdd; 
    $("#NoPermissioniframe").attr("src", frameSrc);  
    $('#NoPermissionModal').modal({ show: true, backdrop: 'static' });
}

//初始化树的公共方法，需要涉及赋值的name、id对象，和树对象
function initTree(nameObj,idObj,treeId){
	settingTree.callback.beforeClick = function(treeId, treeNode) {
		$(nameObj).val(treeNode.name);
		//显式重置所属组织的验证标记
		if($('#sysStaffObjectForm').data('bootstrapValidator')){
			$('#sysStaffObjectForm').data('bootstrapValidator').updateStatus('orgName', 'NOT_VALIDATED', null).validateField('orgName');
		}
		$(idObj).val(treeNode.id);
	}
	//加载添加表单中的所属组织
	$.fn.zTree.init($(treeId), settingTree, treeArray);
}
//展示树的公共方法，需要传递 name的input对象,用于显示的div对象
function showTree(nameObj,divId){
	var parentObj = $(nameObj);
	var parentOffset = $(nameObj).offset();
	$(divId).css({left:parentOffset.left + "px", top:parentOffset.top + parentObj.outerHeight() + "px"}).slideDown("fast");
}
//绑定消除树事件
$("html").bind("mousedown",{view : this},function(event){
		if (!(event.target.id == "faDIV" || $(event.target).parents("#faDIV").length>0)) {
		  	  	$("#faDIV").fadeOut("fast");
		  	}
		if (!(event.target.id == "searchHomeOrgDIV" || $(event.target).parents("#searchHomeOrgDIV").length>0)) {
	  	  	$("#searchHomeOrgDIV").fadeOut("fast");
	  	}
		if (!(event.target.id == "searchPartnerOrgDIV" || $(event.target).parents("#searchPartnerOrgDIV").length>0)) {
	  	  	$("#searchPartnerOrgDIV").fadeOut("fast");
	  	}
	});

// 保存人员及岗位信息
function saveSysStaff(){
	confirmModel("确认新增人员信息？",function(){
		$('#_frm_confirm_modal').modal('hide');
		var name = $('#staffNameStaffObj').val();
		var mobilPhone = $('#mobilPhoneStaffObj').val();
		var account = $('#loginNameStaffObj').val();
		var passwd = $('#passwdStaffObj').val();
		//岗位名称
		var orgName = $('#orgNameStaffObj').val();
		if(name == ''){
			alertModel("请输入人员名字");
		}else if(mobilPhone == ''){
			alertModel("请输入手机号码");
		}else if(account == ''){
			alertModel("请输入账号");
		}else if(passwd == ''){
			alertModel("新增人员时密码不能为空")
		}else if(!checkAccount){
			alertModel("账号已经被占用请修改后提交");
		}else if('' == orgName){
			alertModel("请选择岗位名称");
		}else{
			$.ajax({
				url:"saveSysStaff.action",
				cache:false,
				data:$('#sysStaffObjectForm').serialize(),
				dataType:"JSON",
				type:"post",
				success:function(data){
					$('#staffContainer').hide();
					$('#myTabContent').show();
					if(data == 'success'){
						alertModel('新增人员信息成功！');
						$('#sysStaffObjectForm').bootstrapValidator('resetForm',true);
						staffSearch();
					}else{
						$('#sysStaffObjectForm').bootstrapValidator('resetForm',true);
						alertModel('新增人员信息失败！！');
					}
				},
				error:function(e){
					//$('#staffContainer').modal('hide');
					$('#staffContainer').hide();
					$('#myTabContent').show();
					$('#sysStaffObjectForm').bootstrapValidator('resetForm',true);
					alertModel("新增人员信息时异常："+e);
				}
			})
		}
	});
}

// 修改信息展示
function showEditPage(id){
	$.post('searchStaffMapById.action',{'id':id},function(data){
		validator.fields.passwd.validators = {
				stringLength: { min: 3, max: 20, message: '请输入3~20个字符' }
		};
		$('#sysStaffObjectForm').bootstrapValidator(validator);
		$('#sysStaffObjectForm input').val('');
		$('#sysStaffObjectForm').bootstrapValidator('resetForm',true);
		$('#idStaffObj').val(id);
		$('#statusStaffObjdiv').show();
		$('#saveBtn').hide();
		$('#updateBtn').show();
		$('#orgName').attr("onclick","");
		// 展示人员信息
		var sysStaff = data.staffInfo;
		for(var col in sysStaff){
			if(col == 'sex'){
				$("#sexStaffObj option[value='"+sysStaff[col]+"']").attr("selected",true);
			}else if(col == 'staffOrgStatus'){
			var temp = sysStaff[col];
			var selected =  document.getElementById("staffStatusStaffObj");
			 for(i=0;i<selected.options.length;i++){
			       if(selected.options[i].value == temp){
			              selected.options[i].selected = true;
			       }
			  }
				//$("#staffStatusStaffObj option[value='"+sysStaff[col]+"']").attr("selected",true);
			}else if(col == 'orgName'){
				$("#orgName").val(sysStaff[col]);
			}else if(col == 'orgId'){
				$("#orgId").val(sysStaff[col]);
			}else if(col == 'passwd'){
				continue;
			}else{
				$('#'+col+'StaffObj').val(sysStaff[col]);
			}
		}
		$(".staffList").hide();
		$(".staffUpdate").show();
	});
}

//判断账号是否已存在
function checkAccountFun(fun){
	var loginName = $('#loginNameStaffObj').val();
	if('' == loginName){
		return;
	}
	$.post('searchOnlyAccount.action?temp='+(new Date().getTime()),{'loginName':loginName},function(data){
		if('' == data){
			checkAccount = true;
		}else{
			if(data.staffId != $('#idStaffObj').val()){
				//alertModel('账号已经被占用');
				$('#sysStaffObjectForm')
	            .data('bootstrapValidator')
	            .updateStatus('loginName', 'INVALID', 'loginNameCheck');
			}else if(fun){
				fun();
			}
		}
	});
}

// 更新人员及岗位信息
function updateSysStaff(){
	confirmModel("确认修改人员信息？",function(){
		$('#_frm_confirm_modal').modal('hide');
		var name = $('#staffNameStaffObj').val();
		var mobilPhone = $('#mobilPhoneStaffObj').val();
		/*if(code == ''){
			alertModel("请输入人员编码");
		}else*/ if(name == ''){
			alertModel("请输入人员名字");
		}else if(mobilPhone == ''){
			alertModel("请输入手机号码");
		}/*else if(account == ''){
			alertModel("请输入账号");
		}*/
		else{
			$.ajax({
				url:"updateSysStaff.action",
				cache:false,
				data:$('#sysStaffObjectForm').serialize(),
				dataType:"JSON",
				type:"post",
				success:function(data){
					$('.staffUpdate').hide();
					$('.staffList').show();
					if(data == 'success'){
						alertModel('修改人员信息成功！');
						$('#sysStaffObjectForm').bootstrapValidator('resetForm',true);
						staffSearch();
					}else if(data == 'faild'){
						alertModel("修改人员信息失败！");
					}
				},
				error:function(e){
					alertModel("修改人员信息时异常："+e);
				}
			})
		}
	});
}


//密码重置
function resetPasswd(id,name){
	confirmModel('确定重置'+name+'的密码吗?',function(){
		$('#_frm_confirm_modal').modal('hide');
		$.ajax({
			url:"updateForResetPasswd.action",
			cache:false,
			data:{staffId:id},
			dataType:"text",
			type:"POST",
			success:function(data){
				if(data){
					alertModel("用户"+name+"的密码重置成功，新密码为" + data);
				}else{
					alertModel("密码重置失败！");
				}
			},
			error:function(XMLHttpRequest, textStatus, errorThrown){
				alertModel("密码重置时异常："+errorThrown);
			}
		});
	});
}

//展示人员信息
function doDetail(staffId) {
	var url = prc + "/sysStaffController/goStaffInfo?staffId="+staffId;
	$("#jump_url").attr("src", url);
	$('#infoModal').modal({
		'show' : true
	});
}
/**
 * 修改岗位状态
 * @param record
 * @param status
 */
function changeStaffOrgStatus(staffOrgId,staffName,orgName,status){
	if('1'===status){
		confirmModel("确认恢复"+staffName+"的岗位："+orgName+"吗？",doChangeStaffOrgStatus,[staffOrgId,status]);
		return;
	}
	confirmModel("确认禁用"+staffName+"的岗位："+orgName+"吗？",doChangeStaffOrgStatus,[staffOrgId,status]);
}
function doChangeStaffOrgStatus(array){
	$.post('doChangeStaffOrgStatus',{"staffOrgId":array[0],"status":array[1]},function(result){
		if(result.flag === 'success'){
			if(array[1]==='0'){
				alertModel("禁用成功");
			}else{
				alertModel("恢复成功");
			}
			if($("#partner").hasClass("active")){//如果当前是乙方标签页激活中
				search4Page(2);
				return;
			}
			search4Page(1);
		}else{
			if(array[1]==='1'){
				alertModel("禁用失败");
			}else{
				alertModel("恢复失败");
			}
		}
	});
}
//岗位的角色设置
function addRoleX(staffOrgId,staffName,orgName){
//	var url = "goSysOrgAndRoleShow.action?id="+id;
//	window.open(url,'',"height=500px,width=1000px,toolbar=no,resizable=yes,location=no,top=150,left=200");
	$("#selectedStaffOrg").html(staffName+" "+orgName);
	$("#selectedStaffRoleId").val(staffOrgId);
	$("#hadRoles").empty();
	$("#notHavingRoles").empty();
	$.post('searchRolesByStaffOrgId',{staffOrgId:staffOrgId},function(array){
		var hadRoles = array.hadRoles;
		var notHavingRoles = array.notHavingRoles;
		for(var i=0;i<hadRoles.length;i++){
			$("#hadRoles").append($("<option value=\""+hadRoles[i].ID+"\">"+hadRoles[i].NAME+"</option>"));
		}
		for(var i=0;i<notHavingRoles.length;i++){
			$("#notHavingRoles").append($("<option value=\""+notHavingRoles[i].ID+"\">"+notHavingRoles[i].NAME+"</option>"));
		}
		//初始化左右选择控件
		$('#notHavingRoles').multiselect({
		       keepRenderingSort: true,
		       right: '#hadRoles',
		       rightAll: '#rightAll',
		       rightSelected: '#rightSelected',
		       leftSelected: '#leftSelected',
		       leftAll: '#leftAll',
		       search: {
		            left: '<input type="text" name="q" class="form-control" style="margin-bottom:10px" placeholder="查询待选..." />',
		            right: '<input type="text" name="q" class="form-control" style="margin-bottom:10px" placeholder="查询已选..." />',
		        },
		        fireSearch: function(value) {
		            return value.length > 0;
		        }
		   });
	});
//	$('#rolesModal').modal({'show':true});
	$(".roleSetting").show();
	$(".staffList").hide();
}
//保存岗位角色设置
function doSaveRoles(){
	var all = "";
    $("#hadRoles option").each(function() {
        all += $(this).attr("value")+",";
    });
    $.post('saveRolesToStaffOrgId',{roles:all,staffOrgId:$("#selectedStaffRoleId").val()},function(result){
    	if(result.flag==='success'){
    		//$('#rolesModal').modal('hide');
    		alertModel("保存成功");
    		$(".roleSetting").hide();
    		$(".staffList").show();
    	}
    });
}
//页面中的返回按钮
function showList(){
	$(".staffUpdate").hide();
	$(".roleSetting").hide();
	$(".staffList").show();
	$("#orgContainer").hide();
	$("#searchTable").DataTable().draw(false);
	
}
$(function(){
	$('#loginNameStaffObj').blur(function(){checkAccountFun()});
   if("1"==$("#currentStaffKind").val()){//如果staffKind=1
	// 加载甲方表格 
	searchTable = $("#searchTable").DataTable(tableOption);
   }else{//如果staffKind=2
	// 加载乙方表格
	var partnerTableOption = tableOption;//复制甲方表格配置，修改其中的查询参数
	partnerTableOption.ajax.data=function(d){// 查询参数
				  	d.staffName = $('#searchStaffName').val();
			    	d.loginName = $('#searchLoginName').val();
			    	d.orgId = $('#searchPartnerOrgId').val();
			    	d.attrc = $('#searchStaffOrgStatus').val();
	            	d.staffKind = 2;
	            	return d;
	            };
	searchTable = $("#searchTable").DataTable(partnerTableOption);
  }
   //初始化三棵树
   initTree($("#orgName"),$("#orgId"),$("#orgTree"));
   initTree($("#searchPartnerOrgName"),$("#searchPartnerOrgId"),$("#orgPartnerTree"));
   initTree($("#searchOrgName"),$("#searchOrgId"),$("#orgHomeTree"));
});


//人员的岗位管理  hurx
function orgManage(staffId,staffName,orgName){
	$("#myTabContent").hide();
	$("#orgManageTitle").html(staffName+"的岗位操作");
	$("#orgContainer").show();
	$("#staffId").val(staffId);
	$("#searchOrgTable").DataTable().destroy();
	searchOrgTable = $("#searchOrgTable").DataTable({
		"ordering": false,// 排序
		"serverSide": true,// 开启服务器模式
		"scrollX": true,// 横向滚动     
		ajax: {
            "type": "POST",
            "url":'getStaffOrg.action',//请求路径
            "contentType": 'application/x-www-form-urlencoded; charset=UTF-8',
            "dataType":'json',
            "data":{"staffId":staffId,"orgId":null} 
		},           
		columns: [// 对应列
		    {"data": null,className: "text-center",visible:false},     
		    {"data": null,className: "text-center",render:function(a,b,c,d){
		        	var staffOrgBtnArray = new Array();
		    		if('F' == c.staffOrgType){
		    			staffOrgBtnArray.push({"name": "修改", "fn": "showOrgEditPage(\'" + c.staffOrgId + "\',\'" + c.staffOrgType + "\')","type": "user-button"});
		    		}else{
		    			staffOrgBtnArray.push({"name": "修改", "fn": "showOrgEditPage(\'" + c.staffOrgId + "\',\'" + c.staffOrgType + "\')","type": "user-button"});
		    			staffOrgBtnArray.push({"name": "删除", "fn": "delOrg(\'" + c.staffOrgId + "\',\'" + c.orgName + "\')", "type": "user-button user-btn-n"});
		    		}
		    		if(hadPermission.dpmanage){
		        	staffOrgBtnArray.push({"name": "数据权限管理", "fn": "goDP(\'" + c.staffOrgId + "\',\'" + c.staffId +"\',\'" + c.orgId + "\')", "type": "user-button"});
		    		}
		        	var context =
			             {
			                 func:staffOrgBtnArray
			                 };
			             var html = template(context);
			             return html;
		        	}
		    },
	        {"data": "staffOrgType",className: "text-center",render: function (a, b, c, d) {
	                if('F' == c.staffOrgType){
	                	return '主岗';
	                }else if('T' == c.staffOrgType){
	                	return '兼职';
	                }else{
	                	return '借调';
	                }
	            }
		    },
	        {"data": "orgName",className: "text-center"},
	        {"data": "staffOrgStatus",className: "text-center",render: function (a, b, c, d) {
	                if('1' == c.staffOrgStatus){
	                	return '有效';
	                }else{
	                	return '无效';
	                }
	            }
	        },
	        {"data": "hireDate",className: "text-center"},
	        {"data": "effectStartDate",className: "text-center"},
	        {"data": "effectEndDate",className: "text-center"},
	        {"data": "duty",className: "text-center"},
	    ],
	    "columnDefs": [
			{// 所有列默认值
				"targets": "_all",
				"defaultContent": ''
			},
		]
		,"dom": 'rt<"bottom"ip><"clear">' //生成样式
	});
}
var checkValidator = {
		message: 'This value is not valid',
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
        	staffOrgName: {
                validators: {
                    notEmpty: {
                        message: '请点击选择组织'
                    }
                }
            },
            duty:{
            	validators : {
    				stringLength: { min: 0, max: 100, message: '请输入不超过100个字符' }
    			}
            }
        },
        submitHandler: function(validator, form, submitButton) {
            // Use Ajax to submit form data
			if($(submitButton).attr('id') == 'addOrgBtn'){
				addStaffOrg();
			}
        	if($(submitButton).attr('id') == 'updateOrgBtn'){
				updateStaffOrg();
			}
        }
};
//返回岗位操作list
function showOrg(){
	$("#orgOperation").hide();
	$("#orgContainer").show();
	$("#addBtn").hide();
	$("#orgOperation input").val("");
	$("#orgOperation select option:first").attr("selected","selected");
	$('#orgForm').bootstrapValidator('resetForm',true);
	orgTree = null;
}
//组织树设置
var orgSetting = {
	view: {
		selectedMulti: false
	},
	data: {
		simpleData: {
			enable: true,
			idKey:"oCode", 
            pIdKey:"pCode"
		}
	},
	callback: {
		beforeClick: function(treeId, treeNode) {
			$('#staffOrgOrgId').val(treeNode.id);
			$('#staffOrgName').val(treeNode.name);
			$('#staffOrgName').change();
			$('#staffOrgCloseModal').click();
		}
	},
	async:{
		enable: true,
		url:"../sysOrgController/disOrgTree",
		autoParam:["oCode","has_bm","orgKind"]
	}
};
//展示新增岗位
function showOrgAddPage(){
//	$(".head-title").hide();
	$("#orgContainer").hide();
	$("#orgOperation").show();
	$("#orgOperationTitle").html("新增岗位");
	$("#staffOrgType").show();
	$("#staffOrgTypeForMajor").hide();
	$("#updateOrgBtn").hide();
	$('#addOrgBtn').show();
	$("#staffOrgStatus").show();
	$("#staffOrgStatus1").hide();
	$("#staffOrgFormId").val($("#staffId").val());
	$.post("../sysOrgController/selectorgTree.action",{"oCode":"","has_bm":"1","orgKind":"1"},function(data){
		orgTree = $.fn.zTree.init($("#staffOrgTree"), orgSetting, data);
	});
	if(null == $('#orgForm').data('bootstrapValidator')) {
		$('#orgForm').bootstrapValidator(checkValidator);
	}
	$('#staffOrgName').on('change', function(e) {
        $('#orgForm')
            .data('bootstrapValidator')
            .updateStatus('staffOrgName', 'NOT_VALIDATED', null)
            .validateField('staffOrgName');
    });
}
//添加岗位
function addStaffOrg(){
	$.ajax({
		url:"addStaffOrg.action",
		data:$("#orgForm").serialize(),
		dataType:"JSON",
		type:"POST",
		success:function(data){
			showOrg();
			orgTree = null;
			searchOrgTable.ajax.reload();
			alertModel("添加成功！");
		},
		error:function(e){
			alertModel("添加失败o_o请重试...");
		}
	})
}
//修改岗位
function showOrgEditPage(staffOrgId,staffOrgType){
	$("#orgOperationTitle").html("修改岗位");
	$("#orgContainer").hide();
	$("#orgOperation").show();
	$("#addOrgBtn").hide();
    $("#updateOrgBtn").show();
    if(null == $('#orgForm').data('bootstrapValidator')) {
		$('#orgForm').bootstrapValidator(checkValidator);
	}
	$('#staffOrgName').on('change', function(e) {
        $('#orgForm')
            .data('bootstrapValidator')
            .updateStatus('staffOrgName', 'NOT_VALIDATED', null)
            .validateField('staffOrgName');
    });
	$.post("../sysOrgController/selectorgTree.action",{"oCode":"","has_bm":"1","orgKind":"1"},function(data){
		orgTree = $.fn.zTree.init($("#staffOrgTree"), orgSetting, data);
	});
	$.post("getStaffOrgByStaffOrgId",{"staffOrgId":staffOrgId},function(data){
		$("#staffOrgId").val(data.staffOrgId);
		$("#staffOrgFormId").val(data.staffId);
		$("#staffOrgOrgId").val(data.orgId);
		$("#staffOrgName").val(data.orgName);
		$("#orgType").val(data.staffOrgType);
		if(data.staffOrgType=="F"){
			$("#staffOrgTypeForMajor").show();
			$("#staffOrgTypeForMajor").val("主岗");
			$("#staffOrgType").hide();
			$("#staffOrgStatus1").show();
			$("#staffOrgStatus").hide();
			$("#staffOrgStatus1").val("有效");
		}else {
			if(data.staffOrgType=="T"){
			$("#parttime").attr("selected","selected");
			}else if(data.staffOrgType=="J"){
			$("#transfer").attr("selected","selected");
			}	
			$("#staffOrgTypeForMajor").hide();
			$('#staffOrgType').show();
			$("#staffOrgStatus").show();
			$("#staffOrgStatus1").hide();
			if(data.staffOrgStatus=="1"){
				$("#inUse").attr("selected","selected");
			}else if(data.staffOrgStatus=="0"){
				$("#outOfUse").attr("selected","selected");
			}
		}
		$("#staffOrgHireDate").val(data.hireDate);
		$("#staffOrgStartDate").val(data.effectStartDate);
		$("#staffOrgEndDate").val(data.effectEndDate);
		$("#duty").val(data.duty);
	});
}
//更新岗位信息
function updateStaffOrg(){
	$.ajax({
		url:"updateStaffOrg.action",
		data:$("#orgForm").serialize(),
		dataType:"JSON",
		type:"POST",
		success:function(data){
			showOrg();
			orgTree = null;
			searchOrgTable.ajax.reload();
			alertModel("更新成功！");
		},
		error:function(e){
			alertModel("更新失败o_o请重试...");
		}
	})
}
//删除岗位（物理删除）
function delOrg(staffOrgId,orgName){
	confirmModel("确认删除岗位"+orgName+"么？（永久删除）",function(){
		$.post("delStaffOrg.action",{"staffOrgId":staffOrgId},function(data){
			alertModel("删除成功！");
			searchOrgTable.ajax.reload();
		})
	});
}
//跳转数据权限管理页面
function goDP(id,staffid,orgid){
	window.open("../dataPermissionController/goDataPermission?id="+id+"&staffId="+staffid+"&orgId="+orgid);
}


//ie9表格显示空白问题
function loadDeferScript(){

	/**修改因为高度问题导致分页下移的问题*/

	if(myBrowser() =="IE9"){
		if($(".DTFC_LeftHeadWrapper").length>0&&$(".DTFC_LeftBodyWrapper").length>0){
			var needChangeHeight = $("#searchTable_wrapper .DTFC_ScrollWrapper").height();
			$("#searchTable_wrapper .DTFC_ScrollWrapper").height((needChangeHeight-65)+"px");
		}
		
	}
}

$(document).on('click','#searchTable_paginate li.paginate_button a',function(){

	setTimeout("loadDeferScript()", 1000);
});
$(document).on('click','#searchOrgTable_paginate li.paginate_button a',function(){

	setTimeout("loadDeferScript()", 1000);
});
